<template>
  <t-link theme="primary"  @click="handleOpen">
      员工列表
  </t-link>
  <t-dialog v-model:visible="visible" attach="body" header="员工列表" width="50%">
      <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="companyUserListCRUD.page"
      column-controller-key="interactionList"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <!-- 员工列表 -->
          <t-button
           
            @click="handleOpenDialog('create', { companyId:props.companyId})"
          >
            新建员工
          </t-button>

          
        </div>
       
      </template>
      <template #status="{ row }">
        <t-switch
          v-model:value="row.status"
          :custom-value="[0, 1]"
          :loading="row.loading"
          @change="handleChangeStatus(row)"
        />
      </template>
      
      <!-- <template #role="{ row }">
        {{simpleRoleList.find((item) => item.id == row.role)?.name}}
      </template> -->
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>


      
      <template #operation="{ row }">
        <t-space break-line>
           <t-link theme="primary" @click="handleOpenDialog('read', { id: row.id })"> 详情 </t-link>
           <t-link theme="primary" @click="handleOpenDialog('update', { id: row.id })" > 编辑 </t-link>
           <!-- 重置密码 -->
          <reset-password :row="{...row, password:''}" />
          <t-popconfirm content="确认删除该用户吗？" @confirm="handleDelete({ id: row.id })" >
            <t-link theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>

      
    <template #footer>
      <t-button theme="default" @click="visible = false">取消</t-button>
      <!-- <t-button :loading="loadingSubmit" @click="handleSelectedIds">保存</t-button> -->
    </template>
  </t-dialog>
   <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly, mode }"
      :api-map="companyUserListCRUD"
      header="*"
      width="35%"
      @request-success="handleDialogRequestSuccess"
    >
 

      <t-form-item label="用户账号" name="userName" :rules="[{ required: true, message: '请输入用户账号' }]">
        <t-input
          v-model:value="formData.userName"
          placeholder="请输入用户账号"
          clearable
          :readonly="mode !== 'create'"
        />
      </t-form-item>
      <t-form-item
        v-if="mode === 'create'"
        label="用户密码"
        name="password"
        :rules="[{ required: true, message: '请输入用户密码' }]"
      >
        <t-input
          v-model:value="formData.password"
          placeholder="请输入用户密码"
          clearable
          :readonly="readonly"
          type="password"
        />
      </t-form-item>
      <t-form-item label="用户昵称" name="userNick" :rules="[{ required: true, message: '请输入用户昵称' }]">
        <t-input v-model:value="formData.userNick" placeholder="请输入用户昵称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item
        label="手机号码"
        name="phone"
        :rules="[
          { required: true, message: '请输入手机号码' },
          { telnumber: true, message: '请输入正确的手机号码' },
        ]"
      >
        <t-input
          v-model:value="formData.phone"
          placeholder="请输入手机号码"
          clearable
          :readonly="readonly"
          maxlength="11"
        />
      </t-form-item>
      
      <t-form-item
        v-if="mode !== 'update'"
        label="状态"
        name="status"
        :rules="[{ required: true, message: '请选择状态' }]"
      >
        <t-radio-group v-model:value="formData.status">
          <t-radio
            v-for="_ in dictionaryStore.get('common_status','number')"
            :key="_.value"
            :value="_.value"
            :readonly="readonly"
          >
            {{ _.label }}
          </t-radio>
        </t-radio-group>
      </t-form-item>
     
    
      
      
    </custom-dialog>
 
</template>

<script setup lang="ts">
import dayjs from 'dayjs';

import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { PropType, ref, useTemplateRef, watch } from 'vue';
import { useDictionaryStore, useUserStore } from '@/store';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';

import listToTree from '@/utils/listToTree';
import Upload from '@/components/upload/index.vue';
import { companyUserListCRUD, updateCompanyUserStatus } from  '@/api/delivery/delivery'
import ResetPassword from './ResetPassword.vue';

// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
const visible = ref(false);
// props
const props = defineProps({
  // 订单ids
  name: {
    type: String,
    required: true,
  },
  companyId: {
    type: Number,
    required: true,
  },
  
});

// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'userName', title: '用户账号' },
  { colKey: 'userNick', title: '用户昵称' },
  // { colKey: 'role', title: '角色' },
  { colKey: 'phone', title: '手机号码 ' },
  { colKey: 'status', title: '状态' },
  { colKey: 'createTime', title: '创建时间', width: 160 },
  { colKey: 'operation', title: '操作', width: 210, fixed: 'right' },
];

// 处理改变状态
const handleChangeStatus = (row: Record<string, any>) => {
  row.loading = true;
  const params = { ...row };
  updateCompanyUserStatus(params)
    .then(() => {
      MessagePlugin.success('编辑成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      row.loading = false;
    });
};

// 处理初始化表格
const handleInitTable = () => {

  const params = {
    companyId: props.companyId,
  };
  customTableRef.value.initTable(params);
};

// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
// 处理已解决
const handleDelete = (params: Record<string, any>) => {
  companyUserListCRUD.delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};

// emits
const emits = defineEmits(['requestSuccess']);
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
   handleInitTable()
};
const handleOpen = () => {
  visible.value = true
  handleInitTable()
}
watch(visible, (newVal) => {
  if(newVal===false) {
    emits('requestSuccess',{mode:'update'});
  }
});
// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>) => {

  return params;
};
</script>
<style lang="less" scoped>
:deep(.t-radio-group .t-radio-button) {
  border: none;
  border-radius: 18px !important;
  margin-left: 11px;
}

:deep(.t-radio-group .t-radio-button.t-is-checked) {
  background-color: #f2f3f5;
}
</style>
